'''
@author: l
@Remark:
结构信息

'''
from app.device.models import Structures
from dvadmin.utils.json_response import SuccessResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class StructuresSerializer(CustomModelSerializer):
    class Meta:
        '''
        序列化器
        '''
        model = Structures
        fields = '__all__'
        read_only_fields = ["id"]


class RoleStructuresSerializer(CustomModelSerializer):
    class Meta:
        '''
        序列化器
        '''
        model = Structures
        fields = ['id', 'name']
        read_only_fields = ["id"]


class StructuresViewSet(CustomModelViewSet):
    '''
    结构信息接口
    list:结构信息查询
    create:结构信息新增
    update:结构信息修改
    retrieve:结构信息单例
    destroy:结构信息删除
    multiple_delete:结构信息多删
    '''
    queryset = Structures.objects.all()
    serializer_class = StructuresSerializer

    # filter_fields = ['creator_id']

    def get_user_structures(self, request):
        """用于前端获取当前角色的路由"""
        user = request.user
        queryset = self.queryset
        is_admin = False
        if not user.is_superuser:
            '''
                如果角色属于管理角色，默认返回所有菜单权限
            '''
            role_admin = user.role.filter(admin=True).first()
            is_admin = role_admin is not None
        else:
            is_admin = True
        if is_admin:
            queryset = Structures.objects.all()
        else:
            Ids = user.role.values_list('structures__id', flat=True)
            queryset = Structures.objects.filter(id__in=Ids)
        serializer = RoleStructuresSerializer(queryset, many=True, request=request)
        data = serializer.data
        return SuccessResponse(data=data, total=len(data), msg="获取成功")
